import os
import re
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


from BladeFerm.Lib.Common import logger as mylog, ROOT_PATH


class GetSessionAndToken():
    def __init__(self, isClose=True):
        options = webdriver.ChromeOptions()
        if isClose:
            options.add_argument('--headless')
        # 设置驱动路径
        driver_path = os.path.join(ROOT_PATH, 'Tools\\chromedriver\\chromedriver.exe')
        self.browser = webdriver.Chrome(executable_path=driver_path, options=options)

    # 登录系统，具体到自己系统时需要自行修改 634832692FFCB971B5F7BD2E9D0D6F85
    def login_system(self, **params):
        username = params['username']
        password = params['password']
        url = params['jira_url']
        try:
            mylog.info(f'open url: {url}')
            self.browser.get(url)
            # 显性等待，直到用户名控件加载出来才进行下一步
            WebDriverWait(self.browser, 10, 0.5).until(EC.presence_of_element_located((By.ID, "username")))
            mylog.info(f'begin input username: {username}')
            self.browser.find_element_by_id("username").send_keys(username)
            self.browser.find_element_by_id("password").send_keys(password)
            time.sleep(0.5)
            self.browser.find_element_by_xpath('//*[@id="submit_psd"]/input').click()
            mylog.info(f'click login')
            res = WebDriverWait(self.browser, 5, 0.5).until_not(
                EC.visibility_of_element_located(('xpath', '//*[@id="submit_psd"]/input')))
            mylog.info(f'login result : {res}')
        except Exception as e:
            mylog.error(e)
            res = False
        mylog.info('登录结果：' + str(res))
        return res

    def openURL(self, url):
        self.browser.get(url)

    def get_cookie(self):
        cookies = self.browser.get_cookies()
        print('cookies:', cookies)
        return cookies

    # 获取sessionid
    def get_sessionid(self):
        # 是要从localStorage中获取还是要从sessionStorage中获取，具体看目标系统存到哪个中
        # window.sessionStorage和直接写sessionStorage是等效的
        # 一定要使用return，不然获取到的一直是None
        # get的Item不一定就叫sessionId，得具体看目标系统把sessionid存到哪个变量中
        sessionid = self.browser.execute_script('return sessionStorage.getItem("sessionId");')

        # 另外sessionid一般都直接通过返回Set-Cookies头设置到Cookie中，所以也可以从Cookie读取
        # 获取浏览器所有Set-Cookie，返回对象是字典列表
        # cookies = self.browser.get_cookies()
        # 获取单项Cookie，是不是叫sessionId取决于系统存成什么变量，单项Cookie是字典
        # cookie = self.browser.get_cookie("sessionId")
        # cookie = cookie["value"]
        # print(f"{cookies}")
        return sessionid

    # 获取token
    def get_token(self, keyName):
        # 是要从localStorage中获取还是要从sessionStorage中获取，具体看目标系统存到哪个中
        # window.sessionStorage和直接写sessionStorage是等效的
        # 一定要使用return，不然获取到的一直是None
        # get的Item不一定就叫token，得具体看目标系统把token存到哪个变量中
        # token = self.browser.execute_script('return sessionStorage.getItem("token");')
        # 'return se.SEConfig.token;'  --- ts登录的tooken
        cmd_js = f'return {keyName};'
        token = None
        n = 0
        while token is None:
            try:
                token = self.browser.execute_script(cmd_js)
                print(f"token: {token}")
            except Exception as e:
                print('Exception: ', e)
                token = None
            finally:
                n += 1
                time.sleep(1)
            if n >= 3:
                break
        return token

    def close_notice(self):
        # 显性等待，直到用户名控件加载出来才进行下一步
        try:
            WebDriverWait(self.browser, 10, 0.5).until(
                EC.presence_of_element_located((By.XPATH, '//div[@class="notice-bottom-right"]/button')))
            closeButton = self.browser.find_element_by_xpath('//div[@class="notice-bottom-right"]/button')
            self.browser.execute_script("arguments[0].click();", closeButton)
        except Exception as e:
            print(f"error: {e}")

    def switch_project(self, project):
        button_down = self.browser.find_element_by_xpath('//div[@id="product-and-project-select-wrapper8"]/div/span')
        button_down.click()
        input_ele = self.browser.find_element_by_xpath('//input[@placeholder="搜索我的项目名称"]')
        input_ele.send_keys(project)
        input_ele.send_keys()
        time.sleep(2)
        target_ele = self.browser.find_elements(By.XPATH,
                                        '//div[@class="el-tree-node__children"]//span[2]')
        mylog.info(f'target_ele：{target_ele}')
        target_ele[-1].click()
        mylog.info(f'切换项目：{project}')
        button_click = self.browser.find_element_by_xpath('//div[@class="el-message-box__btns"]/div[2]/button')
        button_click.click()
        return True

    def open_script(self):
        menu_one = self.browser.find_element_by_xpath('//div[@class="el-submenu__title"]/span[contains(text(),"测试设计")]//parent::div')
        menu_one.click()
        menu_two = self.browser.find_element_by_xpath('//li[contains(text(),"测试脚本")]//parent::ul')
        menu_two.click()
        mylog.info(f'打开菜单：测试脚本')
        return True

    def close(self):
        # 退出程序时关闭浏览器
        self.browser.close()


def get_jsession(params):
    '''
    登录获取cookie或者token
    :param params: {'username': 'lijk34925', 'password': 'eGluZ0AyMDIx', 'getToken': True, 'isClose': True,
        'jira_url': 'https://hs-cas.hundsun.com/cas/login?service=https%3A%2F%2Fts.hundsun.com%2Fse%2Fj_spring_cas_security_check',
        }
    :return:
    '''
    cookies = ''
    obj = GetSessionAndToken(params.get('isClose', False))
    # 登录获取cookies
    index = 0
    result_login = False
    while index < 3:
        result = obj.login_system(**params)
        if result:
            result_login = True
            break
        index += 1
        time.sleep(1)
        mylog.warning(f'Retry login ,index : {index}')
    if not result_login:
        obj.close()
        mylog.error(f'登录失败')
        return cookies
    else:
        obj.close_notice()
    # 切换项目
    project = params.get('project')
    obj.switch_project(project)
    time.sleep(0.5)
    cookies_list = obj.get_cookie()
    if params.get('getToken'):
        tooken = obj.get_token('se.SEConfig.token')
        tookenstr = f'token={tooken};'
        cookies += tookenstr
    obj.close()
    for dic in cookies_list:
        name = dic['name']
        value = dic['value']
        t_info = f'{name}={value}; '
        cookies += t_info
    cookies = cookies.rstrip('; ')
    mylog.info(f'cookies: {cookies}')
    return cookies


def get_platform_session(params):
    '''
        登录获取cookie或者token
        :param params: {'username': 'lijk34925', 'password': 'eGluZ0AyMDIx', 'getToken': True, 'isClose': True,
            'jira_url': 'https://hs-cas.hundsun.com/cas/login?service=https%3A%2F%2Fts.hundsun.com%2Fse%2Fj_spring_cas_security_check',
            }
        :return:
        '''
    cookies = ''
    obj = GetSessionAndToken(params.get('isClose', False))
    # 登录获取cookies
    index = 0
    result_login = False
    while index < 3:
        result = obj.login_system(**params)
        if result:
            result_login = True
            break
        index += 1
        time.sleep(1)
        mylog.warning(f'Retry login ,index : {index}')
    if not result_login:
        obj.close()
        mylog.error(f'登录失败')
        return cookies
    else:
        obj.close_notice()
    cookies = obj.get_cookie()
    return cookies


if __name__ == "__main__":
    login_info = {'username': 'lijk34925', 'password': 'ljk8087@', 'getToken': False, 'isClose': True,
        'jira_url': 'https://blade.hundsun.com/blade/index', 'project': '金融反洗钱项目'
        }
    # cookies = get_jsession(**login_info)
    login_platform = {'username': 'lijk34925', 'password': 'ljk2024@', 'getToken': False, 'isClose': False,
                  'jira_url': 'https://hs-cas.hundsun.com/cas/login?service=https%3A%2F%2Fdev.hundsun.com%2FframeV2%2Fpms%2Fworkbench', 'project': '金融反洗钱项目'
                  }
    cookies = get_platform_session(login_platform)
    print('cookies:', cookies)